#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "gameboard.h"
#include <QRandomGenerator>
#include <QMessageBox>
#include <QPushButton>
#include <QDialog>
#include <QVBoxLayout>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent, int playerCount)
    : QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_playerCount(qBound(2, playerCount, 3)),
    m_currentPlayer(0),
    m_positions({0, 0, 0}),
    m_gameOver(false)
{
    ui->setupUi(this);

    // 初始化游戏棋盘
    m_gameBoard = ui->gameBoard;
    m_gameBoard->setPlayerVisible(2, m_playerCount == 3);

    // 设置玩家选择下拉框
    ui->playerComboBox->addItems({"2人游戏", "3人游戏"});
    ui->playerComboBox->setCurrentIndex(m_playerCount - 2);

    // 更新初始状态
    updateStatus();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_rollButton_clicked()
{
    if(m_gameOver) return;

    // 生成骰子点数
    int dice = QRandomGenerator::global()->bounded(1, 7);

    // 创建骰子结果对话框
    QDialog diceDialog(this);
    diceDialog.setWindowTitle("骰子结果");
    diceDialog.setFixedSize(200, 150);

    QLabel diceLabel(QString::number(dice), &diceDialog);
    diceLabel.setAlignment(Qt::AlignCenter);
    diceLabel.setStyleSheet("font-size: 48px; color: #E91E63;");

    QPushButton confirmBtn("确定", &diceDialog);
    confirmBtn.setStyleSheet("padding: 8px; background: #4CAF50; color: white;");

    QVBoxLayout layout(&diceDialog);
    layout.addWidget(&diceLabel);
    layout.addWidget(&confirmBtn);

    // 连接确定按钮信号
    connect(&confirmBtn, &QPushButton::clicked, &diceDialog, &QDialog::accept);

    if(diceDialog.exec() == QDialog::Accepted) {
        processDiceResult(dice);
    }
}

void MainWindow::processDiceResult(int dice)
{
    int& currentPos = m_positions[m_currentPlayer];
    int newPos = currentPos + dice;

    // 精确终点处理
    currentPos = (newPos >= 80) ? 80 : newPos;
    m_gameBoard->movePlayer(m_currentPlayer, currentPos);
    updateStatus();

    // 胜利判断
    if(currentPos == 80) {
        showVictory();
        return;
    }

    // 处理特殊格子
    GridType type = m_gameBoard->getGridType(currentPos);
    if(type != Normal) {
        handleSpecialGrid(type, currentPos);
    }

    // 切换玩家（除非有额外回合）
    if(type != ExtraTurn) {
        m_currentPlayer = (m_currentPlayer + 1) % m_playerCount;
        updateStatus();
    }
}

void MainWindow::handleSpecialGrid(int type, int &position)
{
    QString message;
    bool needMove = true;

    switch(static_cast<GridType>(type)) {
    case BackToStart:
        message = "触发【回到起点】效果！";
        position = 0;
        break;
    case Forward3:
        message = "触发【前进3格】效果！";
        position = qMin(position + 3, 80);
        break;
    case Backward5:
        message = "触发【后退5格】效果！";
        position = qMax(position - 5, 0);
        break;
    case TeleportEnd:
        message = "触发【直达终点】效果！";
        position = 80;
        break;
    case ExtraTurn:
        message = "获得【额外回合】！";
        needMove = false;
        break;
    default:
        return;
    }

    QMessageBox::information(this, "特殊事件", message);

    if(needMove) {
        m_gameBoard->movePlayer(m_currentPlayer, position);
        updateStatus();
        if(position == 80) showVictory();
    }
}

void MainWindow::on_resetButton_clicked()
{
    m_positions.fill(0);
    m_currentPlayer = 0;
    m_gameOver = false;
    m_gameBoard->reset();
    updateStatus();
    ui->rollButton->setEnabled(true);
}

void MainWindow::on_playerComboBox_currentIndexChanged(int index)
{
    m_playerCount = index + 2;
    m_gameBoard->setPlayerVisible(2, m_playerCount == 3);
    on_resetButton_clicked();
}

void MainWindow::showVictory()
{
    m_gameOver = true;
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("游戏胜利");
    msgBox.setText(QString("玩家 %1 获得胜利！").arg(m_currentPlayer + 1));
    msgBox.setIconPixmap(QPixmap(":/icons/victory.png").scaled(64, 64));

    QPushButton *newGame = msgBox.addButton("新游戏", QMessageBox::AcceptRole);
    QPushButton *quit = msgBox.addButton("退出", QMessageBox::RejectRole);
    newGame->setStyleSheet("background: #2196F3; color: white;");
    quit->setStyleSheet("background: #F44336; color: white;");

    if(msgBox.exec() == QMessageBox::AcceptRole) {
        on_resetButton_clicked();
    } else {
        close();
    }
}

void MainWindow::updateStatus()
{
    QStringList positions;
    for(int i = 0; i < m_playerCount; ++i) {
        positions << QString("玩家%1: %2").arg(i+1).arg(m_positions[i]);
    }

    // 更新界面显示
    ui->statusLabel->setText(QString("当前玩家：玩家%1").arg(m_currentPlayer + 1));
    ui->positionsLabel->setText(positions.join(" ｜ "));
    ui->rollButton->setEnabled(!m_gameOver);
}
